import {SaprePartApplySelectedMaterial} from '../types';
import {computed, ref, watch} from 'vue';
import _ from 'lodash';

const sparePartApplyMaterialSelectedList = ref<
	Array<SaprePartApplySelectedMaterial>
>([]);

/**
 * 配件申请单,物料选择列表服务
 */
export default function () {
	const materialSelectedList = ref<Array<SaprePartApplySelectedMaterial>>([]);

	const materialIsBomSelectedSpareIdList = computed(() => {
		return sparePartApplyMaterialSelectedList.value
			.filter((item) => item.isBom === 1)
			.map((item) => item.spareId);
	});

	const materialIsBomSelectedSpecIdList = computed(() => {
		return sparePartApplyMaterialSelectedList.value
			.filter((item) => item.isBom === 1)
			.map((item) => item.specId);
	});

	const materialIsNotBomSelectedSpareIdList = computed(() => {
		return sparePartApplyMaterialSelectedList.value
			.filter((item) => item.isBom === 0)
			.map((item) => item.spareId);
	});

	const materialIsNotBomSelectedSpecIdList = computed(() => {
		return sparePartApplyMaterialSelectedList.value
			.filter((item) => item.isBom === 0)
			.map((item) => item.specId);
	});

	const addSelectedMaterial = (data: SaprePartApplySelectedMaterial) => {
		const index = sparePartApplyMaterialSelectedList.value.findIndex(
			(item) => item.spareId === data.spareId && item.specId === data.specId,
		);
		if (index === -1) {
			sparePartApplyMaterialSelectedList.value.push(_.cloneDeep(data));
		}
	};

	const clearMaterialSelectedList = () => {
		sparePartApplyMaterialSelectedList.value.length = 0;
	};

	const removeSelectedMaterial = (spareId: string, specId: string) => {
		const index = sparePartApplyMaterialSelectedList.value.findIndex(
			(item) => item.spareId === spareId && item.specId === specId,
		);
		if (index >= 0) {
			sparePartApplyMaterialSelectedList.value.splice(index, 1);
		}
	};

	watch(
		() => sparePartApplyMaterialSelectedList.value,
		(value) => {
			materialSelectedList.value = _.cloneDeep(value);
		},
		{deep: true, immediate: true},
	);

	return {
		materialSelectedList,
		materialIsBomSelectedSpareIdList,
		materialIsBomSelectedSpecIdList,
		materialIsNotBomSelectedSpareIdList,
		materialIsNotBomSelectedSpecIdList,
		addSelectedMaterial,
		removeSelectedMaterial,
		clearMaterialSelectedList,
	};
}
